<?php

namespace App\Admin\Controllers;

use App\Admin\Grid\NGrid;
use App\Admin\Tools\Finance\ExpenseDeleteTool;
use App\Admin\Tools\Finance\ExpenseEditTool;
use App\Models\AdminUsersRelatedModel;
use App\Models\ContractedCustomerModel;
use App\Models\FinanceExpensesModel;
use App\Utils\NumberToChinese;
use Encore\Admin\Admin;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Form;
use Encore\Admin\Grid\Displayers\Actions;
use Encore\Admin\Grid\Tools;
use Encore\Admin\Show;
use Illuminate\Support\Facades\Auth;

class FinanceExpensesController extends AdminController
{
    protected $title = '财务支出';

    public function grid(): NGrid
    {
        $grid = new NGrid(new FinanceExpensesModel());
        $grid->model()
            ->leftJoin('contracted_customer', 'contracted_customer.id', 'finance_expenses.contracted_customer_id')
            ->leftJoin('admin_users', 'admin_users.id', 'finance_expenses.operate_id')
            ->orderByDesc('finance_expenses.created_at')
            ->select([
                'finance_expenses.*',
                'admin_users.name as operate_name',
                'contracted_customer.male_name as male_name',
                'contracted_customer.female_name as female_name',
                'contract_no',
                'contract_amount',
            ]);

        $grid->filter(function ($filter) {
            $filter->disableIdFilter();
            $filter->column(1 / 2, function ($filter) {
                $filter->like('finance_expenses-name', '名称');
//                $filter->equal('type', '事由')->select(__('finance_expenses.typeArr'));
                $filter->equal('contracted_customer_id', '客户信息')->select((new ContractedCustomerModel)->customerSelect());
                $filter->between('date', '日期')->date();
            });
            $filter->column(1 / 2, function ($filter) {
                $filter->equal('finance_expenses-status', '状态')->select(__('l.auditStatusArr'));
                $filter->equal('finance_expenses-operate_id', '操作人')->select((new AdminUsersRelatedModel)->stuff());
                $filter->like('finance_expenses-remark', __('l.remark'));
            });
        });

//        if (!ISADMIN) {
//            if (ISMAIN) $grid->model()->where('finance_expenses.main_id', USERID);
//            else $grid->model()->where('finance_expenses.main_id', MAINID);
//        } else $grid->model()->where('finance_expenses.operate_id', USERID);

        if (!ISADMIN) {
            if (in_array(Auth::user()->roles->first()->slug, ['boss', 'finance'])) $grid->model()->where('finance_expenses.main_id', MAINID);
            else $grid->model()->where('finance_expenses.operate_id', USERID);
        }
        $grid->header(function ($query) {
            $success = FinanceExpensesModel::query()->where('status', 1);
            if (!ISADMIN) {
                if (ISMAIN) $success->where('finance_expenses.main_id', USERID);
                else $success->where('finance_expenses.main_id', MAINID);
            } else $success->where('finance_expenses.operate_id', USERID);
            $success = $success->sum('amount');

            $refuse = FinanceExpensesModel::query()->where('status', 0);
            if (!ISADMIN) {
                if (ISMAIN) $refuse->where('finance_expenses.main_id', USERID);
                else  $refuse->where('finance_expenses.main_id', MAINID);
            } else  $refuse->where('finance_expenses.operate_id', USERID);
            $refuse = $refuse->sum('amount');

            return '已审核：' . $success . '（元）待审核：' . $refuse . '（元）';
        });
        if (Auth::user()->roles->first()->slug == 'Administrator') $grid->column('id', 'ID')->sortable();
        $grid->column('date', '支出日期')->style("text-align:center;");
        $grid->column('name', '名称');
        $grid->column('customer_info', '客户信息')->display(function () {
            return $this->contract_no . '-'
                . $this->male_name . '-' . $this->female_name . '-' . $this->contract_amount;
        });
        $grid->column('num', '数量');
        $grid->column('amount', '金额');
        $grid->column('type', '类别')->using(__('finance_expenses.typeArr'));
        $grid->column('invoice_type', '发票类型')->using(__('finance_expenses.invoiceTypeArr'));
        $grid->column('invoice_proof', '凭证')->display(function () {
            if (empty($this->invoice_proof)) return null;
            else {
                $arr = [];
                foreach ($this->invoice_proof as $v) {
                    if ($v !== '') $arr[] = config('env.app_url') . '/upload/' . $v;
                }
                return view('images', ['id' => $this->id, 'image' => $arr]);
//                if (!empty($arr)) return view('images', ['id' => $this->id, 'image' => $arr]);
//                else return null;
            }
        });
        $grid->column('remark', __('l.remark'))->display(function () {
            if (mb_strlen($this->remark) < 16) return $this->remark;
            else return view('tooltip ', [
                'data' => $this->remark
            ]);
        });
        $grid->column('operate_name', '操作人');
        $grid->column('created_at', __('l.createdAt'))->display(function () {
            return date('Y-m-d H:i:s', strtotime($this->created_at));
        });
        $grid->column('status', __('l.status'))->display(function () {
            return $this->status === 0 ? '待审核' : __('l.auditStatusArr')[$this->status];
        });
        $grid->column('audit_remark', __('finance_income.auditRemark'))->display(function () {
            if (mb_strlen($this->audit_remark) < 12) return $this->audit_remark;
            else return view('tooltip ', [
                'data' => $this->audit_remark
            ]);
        });
        $grid->actions(function (Actions $action) {
//            $action->disableEdit();
            $action->disableDelete();
            $action->disableView();
            if ((int)$action->row->status === 1) $action->disableEdit();
//            $action->disableEdit(false);
//            if ((int)$action->row->status !== 1) $action->append(new ExpenseDeleteTool($action->row->id));
        });
        $grid->disableActions(false);
        $grid->disableCreateButton();
        return $grid;
    }

    public function form(): Form
    {
        $form = new Form(new FinanceExpensesModel);
        $form->column(1 / 2, function (Form $form) {
            $form->hidden('id');
            $form->hidden('operate_id');
            $form->hidden('main_id');
            $form->hidden('follow_user_id');
            $form->text('name', '名称');
            $form->select('contracted_customer_id', '客户名')->options((new ContractedCustomerModel)->customerSelect())->required();
            $form->number('num', '数量');
            // 原始金额字段（输入用）
            $form->currency('amount', '金额')->symbol('¥');
            // 显示中文大写（只读）
            $form->text('amount_display', '金额大写')->placeholder('大写金额')->disable();

            Admin::script(<<<SCRIPT
                $("input[name='amount']").on('input', function(e) {
                    const amount = $(this).val();
                    $.ajax({
                        url: '/admin/ajax/numberToChinese', // 自定义接口路由
                        type: 'post',
                        data: {
                            amount: amount,
                            _token: $.admin.token
                        },
                        success: function(response) {
                        console.log(response);
                            $("#amount_display").val(response.data);
                        }
                    });
                });
            SCRIPT);

            $form->date('date', '支出日期')->format('YYYY-MM-DD')->default(date('Y-m-d'));
            $form->select('type', '类别')->options(__('finance_expenses.typeArr'));
            $form->select('invoice_type', '发票类型')->options(__('finance_expenses.invoiceTypeArr'));
            $form->multipleImage('invoice_proof', '凭证')->removable()
                ->dir('/upload/' . now()->year . '/' . now()->month . '/' . now()->day)
                ->name(function ($file) {
                    return $file->getClientOriginalName();
                });
        });

        $form->column(1 / 2, function (Form $form) {
            $form->textarea('remark', __('l.remark'))->rows(10);
        });

        $form->saving(function (Form $form) {
            $contracted = ContractedCustomerModel::query()
                ->where('id', $form->contracted_customer_id)->first();
            $income = FinanceExpensesModel::query()
                ->where('contracted_customer_id',
                    $form->contracted_customer_id)
                ->orderByDesc('id')
                ->first();
//            if ($form->isEditing()) {
//                if ($form->invoice_proof !== '_file_del_') {
//                    $model = FinanceExpensesModel::query()->where('id', $form->id)->first();
//                    $aa = json_encode(
//                        array_values(array_filter($model->invoice_proof, function ($value) {
//                            return $value !== '';
//                        }))
//                    );
//                    $form->invoice_proof = empty($aa) ? null : $aa;
//                }
//            }
//            dd($form->invoice_proof);
            if ($form->isCreating()) $form->operate_id = auth()->user()->id;
            $form->income_received = is_null($income) ? $form->actual_income_amount : bcadd($form->actual_income_amount, $income->income_received, 2);
            if (!is_null($contracted)) $form->follow_user_id = $contracted->operate_id;
            $form->main_id = MAINID;
        });
        return $form->confirm('确定提交吗');
    }

    public function detail()
    {
        $show = new Show(new FinanceExpensesModel);
        $show->invoice_proof('ID');
        return $show;
    }
}
